<?php
use think\Db;
use Wechat\Loader;
function apk_verison_compare($versionA, $versionB) {
	if ($versionA > 2147483646 || $versionB > 2147483646) {
		throw new Exception('版本号,位数太大暂不支持!', '101');
	}
	$dm = '.';
	$verListA = explode($dm, (string)$versionA);
	$verListB = explode($dm, (string)$versionB);

	$len = max(count($verListA), count($verListB));
	$i = -1;
	while ($i++ < $len) {
		$verListA[$i] = intval(@$verListA[$i]);
		if ($verListA[$i] < 0) {
			$verListA[$i] = 0;
		}
		$verListB[$i] = intval(@$verListB[$i]);
		if ($verListB[$i] < 0) {
			$verListB[$i] = 0;
		}

		if ($verListA[$i] > $verListB[$i]) {
			return 1;
		} else if ($verListA[$i] < $verListB[$i]) {
			return -1;
		} else if ($i == ($len - 1)) {
			return 0;
		}
	}

}

/**
 * =========================
 * =======业务扩展 函数库=======
 * =========================
 */

/**
 * 获得工资范围
 */
function get_comment_score($id = 0, $array = false) {
	if ($array) {
		$types['3'] = '好评';
		$types['2'] = '中评';
		$types['1'] = '差评';
		return $types;
	} else {
		switch($id) {
			case 3 :
				return '好评';
				break;
			case 2 :
				return '中评';
				break;
			case 1 :
				return '差评';
				break;
			default :
				return null;
				break;
		}
	}
}




/**
 * 获取微信操作对象
 * @staticvar array $wechat
 * @param type $type
 * @return WechatReceive
 */
function load_wechat($type = '') {
	$wechat = array();
	$index = md5(strtolower($type));
	if (!isset($wechat[$index])) {
		$config = config('wechat');
		$config['cachepath'] = CACHE_PATH . 'wechat';
		$wechat[$index] = Wechat\Loader::get($type, $config);
	}
	return $wechat[$index];
}

/**
 * =========================
 * ========通用 函数库=========
 * =========================
 */


function strFilter($str) {
	$str = str_replace('·', '', $str);
	$str = str_replace('~', '', $str);
	$str = str_replace('!', '', $str);
	$str = str_replace('@', '', $str);
	$str = str_replace('#', '', $str);
	$str = str_replace('$', '', $str);
	$str = str_replace('%', '', $str);
	$str = str_replace('^', '', $str);
	$str = str_replace('&', '', $str);
	$str = str_replace('*', '', $str);
	$str = str_replace('(', '', $str);
	$str = str_replace(')', '', $str);
	$str = str_replace('-', '', $str);
	$str = str_replace('_', '', $str);
	$str = str_replace('——', '', $str);
	$str = str_replace('+', '', $str);
	$str = str_replace('=', '', $str);
	$str = str_replace('|', '', $str);
	$str = str_replace('\\', '', $str);
	$str = str_replace('[', '', $str);
	$str = str_replace(']', '', $str);
	$str = str_replace('{', '', $str);
	$str = str_replace('}', '', $str);
	$str = str_replace(';', '', $str);
	$str = str_replace(':', '', $str);
	$str = str_replace('\'', '', $str);
	$str = str_replace('"', '', $str);
	$str = str_replace(',', '', $str);
	$str = str_replace('<', '', $str);
	$str = str_replace('>', '', $str);
	$str = str_replace('.', '', $str);
	$str = str_replace('/', '', $str);
	$str = str_replace('?', '', $str);
	return trim($str);
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
	$units = array(
		' B',
		' KB',
		' MB',
		' GB',
		' TB',
		' PB'
	);
	for ($i = 0; $size >= 1024 && $i < 5; $i++)
		$size /= 1024;
	return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 获取当前request参数数组,去除值为空
 * @return array
 */
function get_query() {
	$param = request()->except(array('s'));
	$rst = array();
	foreach ($param as $k => $v) {
		if (!empty($v)) {
			$rst[$k] = $v;
		}
	}
	return array('query' => $rst);
}

/**
 * 数组里删除指定key的数据
 */
function array_remove($data, $key) {
	if (!array_key_exists($key, $data)) {
		return $data;
	}
	$keys = array_keys($data);
	$index = array_search($key, $keys);
	if ($index !== FALSE) {
		array_splice($data, $index, 1);
	}
	return $data;
}

/**
 * 数组层级缩进转换
 * @param array $array
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1) {
	static $list = array();
	foreach ($array as $v) {
		if ($v['pid'] == $pid) {
			$v['level'] = $level;
			$list[] = $v;
			array2level($array, $v['id'], $level + 1);
		}
	}

	return $list;
}

/**
 * 构建层级（树状）数组
 * @param array  $array 要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid 父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid = 'pid', $child_key_name = 'children') {
	$counter = array_children_count($array, $pid);
	if ($counter[0] == 0) {

		return false;
	}
	$tree = array();
	while (isset($counter[0]) && $counter[0] > 0) {
		$temp = array_shift($array);
		if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
			array_push($array, $temp);
		} else {
			if ($temp[$pid] == 0) {
				$tree[] = $temp;
			} else {
				$array = array_child_append($array, $temp[$pid], $temp, $child_key_name);
			}
		}
		$counter = array_children_count($array, $pid);
	}
	return $tree;
}

/**
 * 子元素计数器
 * @param $array
 * @param $pid
 * @return array
 */
function array_children_count($array, $pid) {
	$counter = array();
	foreach ($array as $item) {
		$count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
		$count++;
		$counter[$item[$pid]] = $count;
	}

	return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name) {
	foreach ($parent as &$item) {
		if ($item['id'] == $pid) {
			if (!isset($item[$child_key_name]))
				$item[$child_key_name] = array();
			$item[$child_key_name][] = $child;
		}
	}

	return $parent;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name) {
	$result = false;
	if (is_dir($dir_name)) {
		if ($handle = opendir($dir_name)) {
			while (false !== ($item = readdir($handle))) {
				if ($item != '.' && $item != '..') {
					if (is_dir($dir_name . DS . $item)) {
						delete_dir_file($dir_name . DS . $item);
					} else {
						unlink($dir_name . DS . $item);
					}
				}
			}
			closedir($handle);
			if (rmdir($dir_name)) {
				$result = true;
			}
		}
	}
	return $result;
}

function build_order_no() {
	return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}


/********************************** 2018-03-18 ***************************************************************/

/******************************====  公共函数 stat ======******************************/

//图片上传
function upload($files){
	include_once ('././vendor/aliyuncs/oss-sdk-php/autoload.php');
    $tmp = base64_decode($files);
    $fn = time()."_".rand(100000, 999999) . ".jpg";
	$fp = '././uploads/image/'. $fn;
	$fp1 = '././uploads/image/'. $fn;
    $res=file_put_contents( $fp, $tmp);
	$ossClient = new \OSS\OssClient('LTAIaqGtJ3JDXJvv', 'Q2kTcyepAHX0VOR44OtszVoyOKE8gl', 'oss-cn-shanghai.aliyuncs.com');
	try{
		$res=$ossClient->uploadFile("long3",$fn,$fp1);
		$src='https://long3.oss-cn-shanghai.aliyuncs.com/'.$fn;
		unlink($fp1);
		return json(["code"=>200,'url'=>$src]);
	} catch(OssException $e) {
		return json(["code"=>404,'msg'=>'上传错误']);
	} 
} 


 
 /**
 * 返回格式化后的当前时间
 */
function now_time() {
	return date('YmdHis', time()).rand(8, true).time();
}


/*
 * 加密--32位密码
 */
function md5_salt($password) {
	return md5(crypt($password, config('salt')));
}

/**
 * 生成订单号
 */
function order_create_no(){
	return date('YmdHis', time()).rand(8, true).time();
}


function sendsms($sign,$mobile,$tempid,$name,$value,$user_ip){
	$cut_time = now_time();
	include_once ('/extend/smsapi/smsDemo.php');
	$msg=sendMess($sign,$mobile,$tempid,$name,$value);
	if($msg->Message=="OK") {
		$data['mobile'] 	= $mobile;
		$data[$name] 		= $value;
		$data['add_time'] 	= $cut_time;
		$data['message'] 	= '发送成功';
		//$data['user_ip'] 	= $user_ip;
		db('verify_code')->insert($data);
		return true;
	}else{
		$data['mobile'] 	= $mobile;
		$data[$name] 		= $value;
		$data['add_time'] 	= $cut_time;
		$data['result'] 	= 0;
		$data['message'] 	= '发送失败:'.$msg->Message;
		//$data['user_ip'] 	= $user_ip;
		db('verify_code')->insert($data);
		$err=$msg->Message;
		return false;
	}
}
/*
 * 检查验证码
 * */ 
function check_sendcode($mobile, $code, $message){
	$where['mobile'] = $mobile;
	$where['code'] = $code;
	$where['message'] = '发送成功';
	$result =db('verify_code')->where($where)->find();
	// 10分钟有效期
	if(time() - strtotime($result['add_time']) > 600){
		return 2;
	}
	if($code == $result['code']){
		return 1;
	}else{
		return -1;
	}
}
	
/**
 * 发送短信验证
 * $mobile 手机号
 * $template_no 模板编号(数据库主键)，注意不是模板ID
 */
function get_code($mobile,$user_ip){
	// 获取短信模板
	$tem_w['title']='用户注册';
	
	$template = db("sys_template")->where($tem_w)->find();
	// 如果是验证码类型，则生成6位验证码
	if($template['type'] == 1){
		$code = rand(100000, 999999);
		$template['params'] = str_replace('${code}', $code, $template['params']);
		$data['code'] = $code;
	}
	$msg=sendsms($template['sign_name'],$mobile,$template['tid'],'code',$code,$user_ip);
	if($msg){
		return json(["code"=>200,"msg"=>'发送成功!']); 
	}else{
		return json(["code"=>408,"msg"=>'发送失败']); 
	}
}

/**
 * 	$goods_list 商品信息
 * 	$memo		订单留言
 *	$address_id 收货地址id
 * 	$order_type 付款类型
 * 
 * 生成订单，
 */
function add_order($goods_list,$order_sn){
	$total_price = 0;
	if (count($goods_list) == count($goods_list, 1)) {
		
		$price = bcmul($goods_list['cost_price'],$goods_list['goods_num'], 2);
		$total_price = bcadd($price, $total_price, 2);
		$agent_info = db('agent')->where('id',$goods_list['agent_id'])->find();
	}else{
		foreach($goods_list as $key=>$value){
			$price = bcmul($value['cost_price'],$value['goods_num'], 2);
			$total_price = bcadd($price, $total_price, 2);
		}
		
		$agent_info = db('agent')->where('id',$goods_list[0]['agent_id'])->find();
	}
	
	
	$order_info['order_sn'] 	= $order_sn;
	$order_info['user_id'] 		= session('user_id');
	$order_info['agent_id'] 	= $agent_info['id'];
	$order_info['agent_name'] 	= $agent_info['agent_name'];
	$order_info['total_price'] 	= $total_price; 
	$order_info['add_time'] 	= now_time();
	
	return db('good_order')->insert($order_info);
}

//更新订单
function update_order($order_id,$order_type,$address_id,$memo){
	
	//获取收货人信息
	$user_address = db('member_address')->where('id',$address_id)->find();

	$order_info['order_type'] 	= $order_type;
	$order_info['consignee'] 	= $user_address['consignee'];
	$order_info['province'] 	= $user_address['province'];
	$order_info['city'] 		= $user_address['city'];
	$order_info['district']	 	= $user_address['district'];
	$order_info['address'] 		= $user_address['address'];
	$order_info['mobile'] 		= $user_address['mobile'];
	$order_info['memo'] 		= $memo;
	
	return db('good_order')->where('id', $order_id)->update($order_info);
}


//生成订单详情
function add_order_item($goods_list,$order_id){
	$result =true;
	
	if (count($goods_list) == count($goods_list, 1)) {
		
	    $total_price = bcmul($goods_list['cost_price'],$goods_list['goods_num'], 2);
	    
		$item_info['order_id'] 		= $order_id;
		$item_info['goods_id'] 		= $goods_list['goods_id'];
		$item_info['nums'] 			= $goods_list['goods_num'];
		$item_info['total_price'] 	= $total_price;
		$item_info['price'] 		= $goods_list['cost_price'];
		$item_info['goods_name'] 	= $goods_list['goods_name'];
		$item_info['thumb'] 		= $goods_list['logo'];
		$item_info['express_type'] 	= $goods_list['express_type'];
		$item_info['add_time'] 		= now_time();
		
		$rest =  db('order_items')->insert($item_info);
		if(!$rest)$result= false;
		
	} else {
	   foreach($goods_list as $key=>$value){
		   	$total_price = bcmul($value['cost_price'],$value['goods_num'], 2);
			
			$item_info['order_id'] 		= $order_id;
			$item_info['goods_id'] 		= $value['goods_id'];
			$item_info['nums'] 			= $value['goods_num'];
			$item_info['total_price'] 	= $total_price;
			$item_info['price'] 		= $value['cost_price'];
			$item_info['goods_name'] 	= $value['goods_name'];
			$item_info['thumb'] 		= $value['logo'];
			$item_info['express_type'] 	= $value['express_type'];
			$item_info['add_time'] 		= now_time();
			
			$rest =  db('order_items')->insert($item_info);
			if(!$rest)$result= false;
	   }
	}
	
	return $result;
}

 


  
//广告分类
function get_ads($id = 1) {
	switch($id) {
		case 1 :
			return '首页广告';
			break;
		case 2 :
			return '健康广告';
			break;
		case 3 :
			return '商城广告';
			break;
		default :
			return '其它广告';
			break;
	}
}





/******************************====  公共函数 end ======******************************/
